﻿#include "mongodb_query_task.h"
#include "mongodb_mgr.h"
#include "detail/mongodb_client.h"
#include "log.h"

MongoDbQueryTask::MongoDbQueryTask(const std::string &instName, const std::string &dbName, const std::string &collectionName, const std::string &queryString, const std::string &fieldsString)
	: m_instName(instName)
	, m_dbName(dbName)
	, m_collectionName(collectionName)
	, m_queryString(queryString)
	, m_fieldsString(fieldsString)
{
	m_taskInstName = "MongoDbQueryTask_" + m_instName;
}

MongoDbQueryTask::~MongoDbQueryTask()
{

}

void MongoDbQueryTask::Process(void *sharedObj)
{
	if (sharedObj == nullptr)
	{
		LOG_ERROR_TO("MongoDbQueryTask", Fmt("task process failure, no find mongodb obj"));
		return;
	}
	MongoDbClient *client = (MongoDbClient *)sharedObj;
	m_result = client->Find(m_dbName, m_collectionName, m_queryString, m_fieldsString);
}

void MongoDbQueryTask::OnCompleted()
{
	if (m_cb)
	{
		m_cb(m_result);
	}
}

void *MongoDbQueryTask::CreateSharedObj(unsigned index)
{
	auto &objs = MongoDbMgr::get_mutable_instance().GetDbInstance(m_instName + "_query");
	if (index >= objs.size())
	{
		return nullptr;
	}
	return objs[index].get();
}